package cc.higou.service.message;

import cc.higou.core.dao.SkuMapper;
import cc.higou.core.pojo.Color;
import cc.higou.core.pojo.Product;
import cc.higou.core.pojo.SuperPojo;
import cc.higou.service.ProductService;
import cc.higou.service.SolrService;
import cc.higou.service.StaticPageService;
import freemarker.template.TemplateException;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.apache.solr.client.solrj.SolrServerException;
import org.springframework.beans.factory.annotation.Autowired;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import java.io.IOException;
import java.util.*;

/**
 * 说明：
 * 自定义消息监听器
 *
 * @author:dongxing
 * @time:--
 */

public class MyMessageListener implements MessageListener {
    @Autowired
    private ProductService productService;

    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private StaticPageService staticPageService;

    @Override
    public void onMessage(Message message) {
        //强转为ActiveMq的message
        ActiveMQTextMessage activeMQTextMessage = (ActiveMQTextMessage) message;
        try {
            String ids = activeMQTextMessage.getText();
            System.out.println("cms:" + ids);
            if (ids == null) {
                return;
            }
            String[] split = ids.split(",");
            for (String id : split) {
                //商品的信息
                Product product = productService.findProductById(Long.parseLong(id));
                //库存的信息
                List<SuperPojo> skus = skuMapper.findSkuByProductId(Long.parseLong(id));
                SuperPojo superPojo = new SuperPojo();
                superPojo.setProperty("product", product);
                superPojo.setProperty("skus", skus);


                HashSet<Color> colors = new HashSet<>();

                //排除商品的库存颜色中相同的颜色
                for (SuperPojo pojo : skus) {
                    Long color_id = Long.parseLong(pojo.get("color_id") + "");
                    String name = (String) pojo.get("colorName");
                    Color color = new Color();
                    color.setId(color_id);
                    color.setName(name);
                    colors.add(color);
                }

                superPojo.put("colors", colors);

                Map<String, Object> hashMap = new HashMap<>();
                hashMap.put("superPojo", superPojo);

                // 开始静态化
                staticPageService.staticProductPage(hashMap, id);

            }


        } catch (JMSException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
